/**
 * 
 */
package com.ryan.framework.dto;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.beans.BeanUtils;

import com.ryan.framework.model.Model;

public class DtoUtil<T extends Dto,M extends Model> {

	private Class<T> t;
	
	private Class<M> m;
	
	private DtoUtil(Class<T> t,Class<M> m){
		this.t = t;
		this.m = m;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static DtoUtil getInstance(Class t,Class m){
		return  new DtoUtil(t,m);
	}
    
    public M convertDto2Model(T dto){
        if (null == dto) {
            return null;
        }
        try {
            M model = m.newInstance();
            BeanUtils.copyProperties(dto, model);
            return model;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public T convertModel2Dto(M model){
        if (null == model) {
            return null;
        }
        try {
            T dto = t.newInstance();
            BeanUtils.copyProperties(model, dto);
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public List<M> convertDtos2Models(List<T> dtos){
        if (null==dtos || dtos.size()==0) {
            return new ArrayList<M>();
        }
        List<M> result = new ArrayList <M> ();
        Iterator<T> it = dtos.iterator();
        while (it.hasNext()) {
            M model = convertDto2Model(it.next());
            result.add(model);
        }
        return result;
    }
    
    public List<M> convertDtos2Models(Set<T> dtos){
        List<T> temp = new ArrayList<T>();
        temp.addAll(dtos);
        return convertDtos2Models(temp);
    }
    
    public List<T> convertModels2Dtos(List<M> models){
        if (null==models || models.size()==0) {
            return new ArrayList<T>();
        }
        List <T> result = new ArrayList <T> ();
        Iterator<M> it = models.iterator();
        while (it.hasNext()) {
            T dto = convertModel2Dto(it.next());
            result.add(dto);
        }
        return result;
    }
    
    public List<T> convertModles2Dtos(Set<M> models){
        List<M> temp = new ArrayList<M>();
        temp.addAll(models);
        return convertModels2Dtos(temp);
    }
}
